package com.hongxun.budget.ui.activity.sg;

import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.hongxun.budget.R;
import com.hongxun.budget.ui.activity.BaseActivity;
import com.hongxun.budget.ui.dialog.ListDialog;
import com.hongxun.budget.ui.fragment.BaseFragment;
import com.hongxun.budget.ui.fragment.sg.EditBasicsWorkInfo;
import com.hongxun.budget.ui.fragment.sg.EditPolePitInfo;
import com.hongxun.budget.ui.fragment.sg.EditAnchorPitInfo;
import com.hongxun.budget.ui.fragment.sg.EditGroundInfo;
import com.hongxun.budget.utils.RecyclerViewUtils;
import com.hongxun.budget.utils.SPUtils;
import com.hongxun.budget.utils.SgDBUtils;
import com.hongxun.budget.utils.SgStrKey;
import com.hongxun.budget.utils.StringUtils;
import com.hongxun.budget.utils.XUtils;
import com.hongxun.entity.ImageUrl;
import com.hongxun.greenentity.tk.DPictureEntity;
import com.hongxun.interfaces.ResponseListener;
import com.jessewu.library.SuperAdapter;
import com.jessewu.library.view.ViewHolder;
import com.previewlibrary.GPreviewBuilder;
import com.yuyh.library.imgsel.ISNav;
import com.yuyh.library.imgsel.common.ImageLoader;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 隐蔽工程信息
 */
public class HideProInfoAddActivity extends BaseActivity {
    @BindView(R.id.center_title)
    TextView centerTitle;
    @BindView(R.id.right_save)
    Button rightSave;
    @BindView(R.id.tv1)
    TextView tv1;
    @BindView(R.id.tvType1)
    TextView tv2;
    @BindView(R.id.tvType2)
    TextView tv3;
    @BindView(R.id.tvTitle2)
    TextView tvTitle2;
    @BindView(R.id.recyview1)
    RecyclerView recyview1;
    @BindView(R.id.recyview2)
    RecyclerView recyview2;

    private TextView currTv;
    private boolean zp1;
    private boolean isNewAdd;
    //new
    private String tabName = "电杆坑";
    private List<String> stringList = new ArrayList<>();
    private BaseFragment baseFragment;
    private EditPolePitInfo ybgcInfo1;
    private EditAnchorPitInfo ybgcInfo2;
    private EditGroundInfo ybgcInfo3;
    private EditBasicsWorkInfo ybgcInfo4;
    private SuperAdapter<DPictureEntity> superAdapter1;
    private SuperAdapter<DPictureEntity> superAdapter2;
    private List<DPictureEntity> photos1 = new ArrayList<>();
    private List<DPictureEntity> photos2 = new ArrayList<>();

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    superAdapter1.notifyDataSetChanged();
                    break;
                case 2:
                    superAdapter2.notifyDataSetChanged();
                    break;
            }
            return false;
        }
    });

    @Override
    public int getLayoutId() {
        return R.layout.sg_activity_hideproinfo_add;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        ISNav.getInstance().init(new ImageLoader() {
            @Override
            public void displayImage(Context context, String path, ImageView imageView) {
                Glide.with(context).load(path).into(imageView);
            }
        });
        tvTitle2.setText("图纸照片");
        isNewAdd = getIntent().getBooleanExtra("isNewAdd", false);
        centerTitle.setText(String.valueOf(SPUtils.get(context, SgStrKey.namexm, "隐蔽工程信息")));
        if (isNewAdd) {
            String itemUuid = StringUtils.getUuid();
            SPUtils.put(context, SgStrKey.uuidxx, itemUuid);
        } else {
            tabName = getIntent().getStringExtra("itemName");
            tv1.setEnabled(false);
            tv1.setText(tabName);
        }
        changeTab();
        recyview1.addItemDecoration(new DividerItemDecoration(context, LinearLayoutManager.HORIZONTAL));
        recyview1.setLayoutManager(RecyclerViewUtils.getLinearLayoutManagerForHorizontal(context));
        recyview1.setAdapter(getsuperAdapter1());
        recyview2.addItemDecoration(new DividerItemDecoration(context, LinearLayoutManager.HORIZONTAL));
        recyview2.setLayoutManager(RecyclerViewUtils.getLinearLayoutManagerForHorizontal(context));
        recyview2.setAdapter(getsuperAdapter2());

        rightSave.setVisibility(View.VISIBLE);
        rightSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (tabName.equals(SgStrKey.dgk)) {
                    ybgcInfo1.saveData(tabName);
                } else if (tabName.equals(SgStrKey.lxk)) {
                    ybgcInfo2.saveData(tabName);
                } else if (tabName.equals(SgStrKey.jdt)) {
                    ybgcInfo3.saveData(tabName);
                } else if (tabName.equals(SgStrKey.sbjc)) {
                    ybgcInfo4.saveData(tabName);
                }
                photos2.addAll(photos1);
                for (DPictureEntity entity : photos2) {
                    SgDBUtils.upDataDPictureEntity(entity);
                }
                finish();
            }
        });
        onrefresh();
    }

    private void onrefresh() {
        photos1.clear();
        photos2.clear();
        new Thread(new Runnable() {
            @Override
            public void run() {
                String value1 = String.valueOf(SPUtils.get(context, SgStrKey.uuidxm, ""));
                String value2 = String.valueOf(SPUtils.get(context, SgStrKey.uuidxx, ""));
                photos1.addAll(SgDBUtils.getDPictureList(value1, value2, "检查,xc"));
                handler.sendEmptyMessage(1);
                photos2.addAll(SgDBUtils.getDPictureList(value1, value2, "检查,tz"));
                handler.sendEmptyMessage(2);
            }
        }).start();
    }

    private RecyclerView.Adapter getsuperAdapter2() {
        superAdapter2 = new SuperAdapter<DPictureEntity>(R.layout.sg_content_photo_label1) {
            @Override
            public void bindView(ViewHolder viewHolder, final DPictureEntity photos, final int i) {
                ImageView imageView = viewHolder.getView(R.id.imageView);
                ImageButton imageButton = viewHolder.getView(R.id.imageButton);
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                XUtils.loadImg(context, SgDBUtils.getUrl(photos), imageView);
                imageButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        photos2.remove(photos);
                        SgDBUtils.delDPictureEntity(photos);
                        handler.sendEmptyMessage(2);
                    }
                });
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        List<ImageUrl> urlList = new ArrayList<>();
                        for (DPictureEntity data : photos2) {
                            String url = String.valueOf(SgDBUtils.getUrl(data));
                            urlList.add(new ImageUrl(url, null));
                        }
                        GPreviewBuilder.from(activity)
                                .setData(urlList)
                                .setCurrentIndex(i)
                                .setSingleFling(false)//是否在黑屏区域点击返回
                                .setDrag(false)//是否禁用图片拖拽返回
                                .setType(GPreviewBuilder.IndicatorType.Number)//指示器类型
                                .start();//启动
                    }
                });
            }
        };
        superAdapter2.setData(photos2);
        return superAdapter2;
    }

    private RecyclerView.Adapter getsuperAdapter1() {
        superAdapter1 = new SuperAdapter<DPictureEntity>(R.layout.sg_content_photo_label1) {
            @Override
            public void bindView(ViewHolder viewHolder, final DPictureEntity photos, final int i) {
                ImageView imageView = viewHolder.getView(R.id.imageView);
                ImageButton imageButton = viewHolder.getView(R.id.imageButton);
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                XUtils.loadImg(context, SgDBUtils.getUrl(photos), imageView);
                imageButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        photos1.remove(photos);
                        SgDBUtils.delDPictureEntity(photos);
                        handler.sendEmptyMessage(1);
                    }
                });
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        List<ImageUrl> urlList = new ArrayList<>();
                        for (DPictureEntity data : photos1) {
                            String url = String.valueOf(SgDBUtils.getUrl(data));
                            urlList.add(new ImageUrl(url, null));
                        }
                        GPreviewBuilder.from(activity)
                                .setData(urlList)
                                .setCurrentIndex(i)
                                .setSingleFling(false)//是否在黑屏区域点击返回
                                .setDrag(false)//是否禁用图片拖拽返回
                                .setType(GPreviewBuilder.IndicatorType.Number)//指示器类型
                                .start();//启动
                    }
                });
            }
        };
        superAdapter1.setData(photos1);
        return superAdapter1;
    }

    private void choiceType(final String title) {
        new ListDialog<String>()
                .setTitle(title)
                .setDatas(stringList)
                .setListener(new ResponseListener() {
                    @Override
                    public void response(Object... data) {
                        currTv.setText(data[0] + "");
                        if (title.contains("隐蔽工程")) {
                            tabName = data[0] + "";
                            changeTab();
                        } else if (title.contains("照片类别")) {
                        } else if (title.contains("图纸类别")) {
                        }
                    }
                }).show(getFragmentManager(), title);
    }

    private void changeTab() {
        Bundle bundle = new Bundle();
        bundle.putBoolean("isNewAdd", isNewAdd);
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        if (baseFragment != null) transaction.hide(baseFragment);
        switch (tabName) {
            case SgStrKey.dgk:
                if (ybgcInfo1 == null) {
                    ybgcInfo1 = new EditPolePitInfo();
                    ybgcInfo1.setArguments(bundle);
                    baseFragment = ybgcInfo1;
                    transaction.add(R.id.flayout1, ybgcInfo1, tabName).commit();
                } else {
                    baseFragment = ybgcInfo1;
                    transaction.show(ybgcInfo1).commit();
                }
                break;
            case SgStrKey.lxk:
                if (ybgcInfo2 == null) {
                    ybgcInfo2 = new EditAnchorPitInfo();
                    ybgcInfo2.setArguments(bundle);
                    baseFragment = ybgcInfo2;
                    transaction.add(R.id.flayout1, ybgcInfo2, tabName).commit();
                } else {
                    baseFragment = ybgcInfo2;
                    transaction.show(ybgcInfo2).commit();
                }
                break;
            case SgStrKey.jdt:
                if (ybgcInfo3 == null) {
                    ybgcInfo3 = new EditGroundInfo();
                    ybgcInfo3.setArguments(bundle);
                    baseFragment = ybgcInfo3;
                    transaction.add(R.id.flayout1, ybgcInfo3, tabName).commit();
                } else {
                    baseFragment = ybgcInfo3;
                    transaction.show(ybgcInfo3).commit();
                }
                break;
            case SgStrKey.sbjc:
                if (ybgcInfo4 == null) {
                    ybgcInfo4 = new EditBasicsWorkInfo();
                    ybgcInfo4.setArguments(bundle);
                    baseFragment = ybgcInfo4;
                    transaction.add(R.id.flayout1, ybgcInfo4, tabName).commit();
                } else {
                    baseFragment = ybgcInfo4;
                    transaction.show(ybgcInfo4).commit();
                }
                break;
        }

    }

    @OnClick({R.id.tv1,
            R.id.tvType1, R.id.tvType2,
            R.id.ivTakePhoto1, R.id.ivTakePhoto2})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv1:
                currTv = (TextView) view;
                stringList.clear();
                stringList.add("电杆坑");
                stringList.add("拉线坑");
                stringList.add("接地体");
                stringList.add("设备基础");
                choiceType("选择隐蔽工程");
                break;
            case R.id.tvType1:
//                currTv = (TextView) view;
//                stringList.clear();
//                stringList.add("全部照片");
//                stringList.add("挖坑情况");
//                stringList.add("土质情况");
//                choiceType("选择照片类别");
                break;
            case R.id.tvType2:
//                currTv = (TextView) view;
//                stringList.clear();
//                stringList.add("全部照片");
//                stringList.add("设计图纸");
//                stringList.add("现场图纸");
//                choiceType("选择图纸类别");
                break;
            case R.id.ivTakePhoto1:
                zp1 = true;
                XUtils.imgClick(activity);
                break;
            case R.id.ivTakePhoto2:
                zp1 = false;
                XUtils.imgClick(activity);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK && data != null) {
            List<String> pathList = new ArrayList<>();
            String resour = "相册";
            if (requestCode == XUtils.CHOISE_IMG) {// 图片选择结果回调
                pathList.addAll(data.getStringArrayListExtra("result"));
            } else if (requestCode == XUtils.CAMERA_IMG) {
                resour = "相机";
                String path = data.getStringExtra("result"); // 图片地址
                pathList.add(path);
            }
            toDPictureEntity(pathList, resour);
        }
    }

    private void toDPictureEntity(List<String> pathList, String resour) {
        for (String s : pathList) {
            DPictureEntity bean = new DPictureEntity();
            bean.setGuid(StringUtils.getUuid());
            bean.setPGuid(String.valueOf(SPUtils.get(context, SgStrKey.uuidxm, "")));//所属项目ID
            bean.setPPGuid(String.valueOf(SPUtils.get(context, SgStrKey.uuidxx, "")));//所属隐蔽工程信息ID
            bean.setPAppaddress(s);
            bean.setPStatus("施工");//固定
            bean.setPDatastate(SgStrKey.add);
            bean.setPPResour(resour);
            bean.setPTime(new Date(System.currentTimeMillis()));
            bean.setPName(s.substring(s.lastIndexOf("/") + 1, s.length()));
            if (zp1) {
                bean.setPLabel("检查,xc");
                photos1.add(0, bean);
            } else {
                bean.setPLabel("检查,tz");
                photos2.add(0, bean);
            }
        }
        if (zp1) {
            handler.sendEmptyMessage(1);
        } else {
            handler.sendEmptyMessage(2);
        }
    }
}
